import { Observer, observer } from 'mobx-react-lite'
import { toJS } from "mobx"
import _ from 'lodash'
import React, { useState } from 'react'

import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  TouchableWithoutFeedback,
  Alert,
  Dimensions,
  SafeAreaView,
  Platform,
  Image,
} from 'react-native'

import { useRoute, useNavigation } from '@react-navigation/native'

import { Placeholder, PlaceholderMedia, PlaceholderLine, Shine } from 'rn-placeholder'
import { useStores } from '../stores'
import {
  Spinner,
  CollapsibleText,
  Button,
  SubscribeButton,
  TagButton,
  Spacer,
  Blank,
  Snackbar
} from '../views'
import i18n from '../i18n'

const BookPlaceHolder = observer(() => {
  const { appearance: ap } = useStores()
  return (
    <Placeholder
      Animation={Shine}
      Left={PlaceholderMedia}
      style={{ ...styles.bookContent, borderBottomColor: ap.theme.tiny }}
    >
      <PlaceholderLine width={40} />
      <PlaceholderLine width={40} />
      <PlaceholderLine />
      <PlaceholderLine width={80} />
      <PlaceholderLine />
    </Placeholder>
  )
})

const Author = ({ author }) => {
  const { appearance: ap, bookApi } = useStores()
  const navigation = useNavigation()
  return (
    <TouchableWithoutFeedback
      onPress={() => navigation.navigate('BookList', { data: author, key: 'author' })}>
      <Text style={{ ...styles.authorText, color: ap.theme.active }}>
        {author.name}
      </Text>
    </TouchableWithoutFeedback>
  )
}

const RelateBooksPlaceHolder = () => (
  <Placeholder
    Animation={Shine}
    style={{}}
  >
    <PlaceholderLine width={60} />
    <PlaceholderLine width={40} />
    <PlaceholderLine />
    <PlaceholderLine width={80} />
  </Placeholder>
)

const RelateBooks = observer(({ api, id, name }) => {
  const { appearance: ap, bookApi } = useStores()
  const navigation = useNavigation()
  const [data, setData] = useState()
  if (!data) {
    api(id).then(data => setData(data[name])).catch(err => {
      Snackbar.error({ text: err.toString(), statusBarBackgroundColor: ap.theme.background })
    })
    return <RelateBooksPlaceHolder />
  }

  return (
    <View style={{ ...styles.relateContainer, backgroundColor: ap.theme.background }}>
      <View style={{ ...styles.relateTitle }}>
        <Text style={{ ...styles.relateTitleMainTxt, color: ap.theme.primary }}>{_.trim(data.name)}</Text>
        <Text style={{ color: ap.theme.second, fontSize: 12, fontWeight: 'bold' }}>•{data.count}{i18n.t('hasBook')}</Text>
        <View style={{ ...styles.relateSubscribeButton }}>
          <SubscribeButton title={i18n.t('subscribe')}
            onPress={() => {
              Snackbar.info({
                text: name,
                statusBarBackgroundColor: ap.theme.background
              })
            }}
          />
        </View>
      </View>
      <View style={{ ...styles.relateBooktileContainer }}>
        {
          data.books.map(b =>
            <TouchableOpacity
              style={{ ...styles.relateBooktile }} key={b._id}
              onPress={() => navigation.push('Book', { _id: b._id, title: b.name })}
            >
              <Image
                style={{ ...styles.relateBookCover }}
                source={{ uri: bookApi.getCoverUrl(b.cover) }}
              />
              <Text style={{ width: 113 * 0.7, paddingTop: 6, fontWeight: 'bold', color: ap.theme.weak }} numberOfLines={2}>{b.name}</Text>
            </TouchableOpacity>

          )
        }
      </View>
      <View style={{ ...styles.relateLookAll }}>
        <TouchableOpacity
          style={{ ...styles.relateLookAllButton, backgroundColor: ap.theme.tiny }}
          activeOpacity={0.6}
          onPress={() => navigation.navigate('BookList', { key: name, data })}>
          <Text style={{ color: ap.theme.second, fontWeight: 'bold' }}>{i18n.t('showAll')}</Text>
        </TouchableOpacity>
      </View>
    </View>
  )
})

const TagsContent = observer(({ tags }) => {
  const { appearance: ap } = useStores()
  return (
    <View style={{ ...styles.tagsContent }}>
      { tags.map(t => (
        <TagButton
          key={t._id}
          title={t.name}
          backgroundColor={ap.theme.surface}
          color={ap.theme.second} />
      ))}
    </View>
  )
})

const BookContent = ({ book }) => {
  const { bookApi, appearance: ap } = useStores()
  return (
    <View style={{ ...styles.bookContent, borderBottomColor: ap.theme.tiny }}>
      <View style={{ ...styles.bookLeft }}>
        <Image style={{ ...styles.bookCover }} source={{ uri: bookApi.getCoverUrl(book.cover) }} />
      </View>
      <View style={{ ...styles.bookRight }}>
        <View style={styles.rightItem}>
          <Text style={{ ...styles.bookTitle, color: ap.theme.primary }}>{book.name}</Text>
        </View>
        <View style={{ ...styles.rightItem, flexDirection: 'row' }}>
          {
            book.authors.map(v =>
              <View style={{ paddingRight: 10 }} key={v._id}>
                <Author author={v} />
              </View>
            )
          }
        </View>
        <View style={styles.rightItem}>
          <CollapsibleText
            numberOfLines={5}
            labels={[i18n.t('expand'), i18n.t('collapse')]}
            expandTextStyle={{ color: ap.theme.active }}
            style={{ color: ap.theme.second, fontSize: 12 }}>
            {book.info}
          </CollapsibleText>
        </View>
      </View>
    </View>
  )
}

const ExtraInfoItem = ({ title = '', content = '', tail = '' }) => {
  const { appearance: ap } = useStores()
  return (
    <View
      style={{ ...styles.extraInfoItem, borderLeftColor: ap.theme.tiny, borderLeftWidth: 1 }} >
      <Text style={{ ...styles.extraInfoItemTitle, color: ap.theme.weak }}>{title}</Text>
      <Text style={{ ...styles.extraInfoItemContent, color: ap.theme.second }}>{content}</Text>
    </View>
  )
}

const TouchableExtraInfoItem = ({ title = '', content = '', tail = '', action = () => { } }) => {
  const { appearance: ap } = useStores()
  return (
    <TouchableOpacity activeOpacity={0.6} onPress={() => action()}
      style={{ ...styles.extraInfoItem, borderLeftColor: ap.theme.tiny, borderLeftWidth: 1 }} >
      <Text style={{ ...styles.extraInfoItemTitle, color: ap.theme.active }}>{title}</Text>
      <Text style={{ ...styles.extraInfoItemContent, color: ap.theme.active }}>{content}</Text>
    </TouchableOpacity>
  )
}

const BookExtraInfo = ({ book }) => {
  const { wordage = 0, chapterCount = 0 } = book
  const navigation = useNavigation()
  if (!book._id) {
    return (
      <Placeholder
        Animation={Shine}
        style={{ ...styles.bookExtraInfo, paddingLeft: 24, paddingRight: 24 }}
      >
        <PlaceholderLine />
        <PlaceholderLine width='80' />
        <PlaceholderLine />
      </Placeholder>
    )
  }
  return (
    <View style={{ ...styles.bookExtraInfo }}>
      <ExtraInfoItem title={i18n.t('readed')} content='123' />
      <ExtraInfoItem title={i18n.t('wordage')} content={`${wordage}`} />
      <TouchableExtraInfoItem
        title={i18n.t('chapters')}
        content={`${chapterCount}`}
        action={() => navigation.navigate('ChapterList', { book })} />
    </View>
  )
}

const BookBottomButtons = ({ book }) => {
  const { appearance: ap } = useStores()
  return (
    <View style={{
      ...styles.bottomButtonsContainer,
      backgroundColor: ap.theme.background,
      borderTopColor: ap.theme.surface
    }}>
      <View style={{ flex: 1, alignItems: 'center' }}>
        <Button title={i18n.t('download')}
          backgroundStyle={{ backgroundColor: ap.theme.tiny }}
          style={{ color: ap.theme.primary }}
          onPress={() => console.log('11')} />
      </View>
      <View style={{ flex: 1, alignItems: 'center' }}>
        <Button title={i18n.t('shelfIt')}
          backgroundStyle={{ backgroundColor: ap.theme.tiny }}
          style={{ color: ap.theme.primary }} />
      </View>
      <View style={{ flex: 1, alignItems: 'center' }}>
        <Button title={i18n.t('reading')} />
      </View>
    </View>
  )
}

const Content = observer(({ book }) => {
  const { appearance: ap, bookApi } = useStores()
  return (
    <SafeAreaView style={styles.container}>
      <ScrollView style={{ ...styles.container, backgroundColor: ap.theme.background }}>
        <BookContent book={book} />

        <TagsContent tags={book.tags} />

        <Spacer />

        <BookExtraInfo book={book} />


        <Spacer />

        {
          book._id && book.categories.map(v =>
            <RelateBooks
              api={id => bookApi.fetchBooksByCategory(id)}
              id={v._id} name={'category'} key={v._id} />
          ) || <View></View>
        }

        <Spacer />

        {
          book._id && book.authors.map(v =>
            <RelateBooks
              api={id => bookApi.fetchBooksByAuthor(id)}
              id={v._id} name={'author'} key={v._id} />
          ) || <View></View>
        }

        <Blank />
      </ScrollView>
      <BookBottomButtons book={book} />
    </SafeAreaView>
  )
})

export default observer(({ navigation, route }) => {
  const { bookApi } = useStores()
  const { title, _id } = route.params
  const [book, setBook] = useState()

  React.useLayoutEffect(() => {
    navigation.setOptions({ title })
  })

  if (!book) {
    bookApi.fetchBook(_id)
      .then(data => setBook(data.book))
      .catch(err => Snackbar.error({ text: err.toString(), statusBarBackgroundColor: ap.theme.background })
      )
    return <BookPlaceHolder />
  }

  return (
    <>
      <Content book={book} />
    </>
  )
})

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },

  bookContent: {
    flexDirection: 'row',
    paddingLeft: 12,
    paddingRight: 12,
    paddingTop: 24,
    paddingBottom: 18,
    // borderBottomWidth: 1,
  },

  bookLeft: {
    flex: 1,
    paddingRight: 16,
  },

  bookRight: {
    flex: 2,
    justifyContent: 'flex-start',
  },

  rightItem: {
    paddingBottom: 10,
  },

  bookCover: {
    height: 150,
    width: 113,
  },

  bookTitle: {
    fontSize: 16,
    fontWeight: 'bold',
  },

  authorText: {
    fontSize: 12,
    fontWeight: 'bold',
  },

  bookExtraInfo: {
    flexDirection: 'row',
    paddingBottom: 6,
    paddingTop: 6,
  },

  extraInfoItem: {
    alignItems: 'center',
    flex: 1,
  },

  extraInfoItemTitle: {
    fontSize: 12,
    fontWeight: 'bold',
  },

  extraInfoItemContent: {
    fontSize: 14,
    fontWeight: 'bold',
    paddingTop: 1,
    paddingBottom: 1,
  },

  bottomButtonsContainer: {
    flexDirection: 'row',
    position: 'absolute',
    flex: 1,
    bottom: 0,
    alignItems: 'center',
    paddingBottom: Platform.OS == 'android' ? 10 : 24,
    paddingTop: 10,
    borderTopWidth: 1,
  },

  relateContainer: {
    paddingLeft: 12,
    paddingRight: 12,
    paddingTop: 20,
    paddingBottom: 18,
    marginBottom: 12,
    flex: 1,
  },

  relateTitle: {
    flexDirection: 'row',
    alignItems: 'center'
  },

  relateTitleMainTxt: {
    fontSize: 16,
    fontWeight: 'bold',
  },

  relateSubscribeButton: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },

  relateBooktileContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingTop: 12,
    justifyContent: 'space-around',
  },

  relateBooktile: {
    // padding: 5,
  },

  relateBookCover: {
    width: 113 * 0.6,
    height: 150 * 0.6,
  },

  relateLookAll: {
    flex: 1,
    alignItems: 'center',
    paddingTop: 12,
  },

  relateLookAllButton: {
    borderRadius: 7,
    alignItems: 'center',
    width: Dimensions.get('window').width * 0.9,
    paddingBottom: 10,
    paddingTop: 10,
  },

  tagsContent: {
    flexDirection: 'row',
    flex: 1,
    flexWrap: 'wrap',
    paddingBottom: 10,
    paddingLeft: 12,
    paddingRight: 12,
  }
})